package com.azhuo.core.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.azhuo.core.pojo.User;

/**
 * 登录拦截器
 * @author azhuo
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		// System.out.println("经过了拦截器");

		// 获取请求URL
		String url = request.getRequestURI();
		// url: 除了登陆、注册请求外，其他的URL都进行拦截控制
		String[] path = {"/login.action", "/toLogin.action", "/regist.action", "/toRegist.action"};
		for(int i=0; i<path.length; i++) {
			if(url.indexOf(path[i]) >= 0) {
				return true;
			}
		}

		// 获取Session
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("USER_SESSION");
		// 判断Session中是否有用户数据，如果有：则用户已经登录
		if (user != null) {
			return true;
		}

		// 没有数据，用户还没有登录
		request.setAttribute("msg", "您还没登录，请先登陆。");
		request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);

		return false;
		
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

}
